import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:video_player/video_player.dart';

import '../../../providers/provider_container.dart';
import '../intent/video_play_state.dart';
import '../model/video_play_viewmodel.dart';

class VideoPlayPage extends ConsumerStatefulWidget {
  final String videoName;

  final String videoUrl;

  VideoPlayPage({required this.videoName, required this.videoUrl});

  @override
  ConsumerState<ConsumerStatefulWidget> createState() {
    return _VideoPlayPageState();
  }
}

class _VideoPlayPageState extends ConsumerState<VideoPlayPage> {
  VideoPlayViewModel get viewModel => ref.read(videoPlayViewModelProvider.notifier);

  @override
  void initState() {
    super.initState();
    print('*************');
    print(widget.videoUrl);
    print('*************');
    WidgetsBinding.instance.addPostFrameCallback((_) {
      viewModel.initData(widget.videoName, widget.videoUrl);
    });
  }

  @override
  Widget build(BuildContext context) {
    final VideoPlayState state = ref.watch(videoPlayViewModelProvider);
    final orientation = MediaQuery.of(context).orientation;
    final size = MediaQuery.of(context).size;
    final isLandscape = orientation == Orientation.landscape;
    return Scaffold(
      backgroundColor: Colors.black,
      body: state.controller?.value.isInitialized == true
          ? isLandscape
                ? _buildFullScreenContent(context, size)
                : SafeArea(child: _buildFullScreenContent(context, size))
          : const Center(child: CircularProgressIndicator()),
    );
  }

  Widget _buildFullScreenContent(BuildContext context, Size size) {
    final VideoPlayState state = ref.watch(videoPlayViewModelProvider);
    return GestureDetector(
      onTap: viewModel.toggleControls, // 点击视频区域切换控制栏显示/隐藏
      child: Stack(
        fit: StackFit.expand,
        children: [
          // 视频显示区域
          FittedBox(
            fit: BoxFit.contain,
            child: SizedBox(width: state.controller!.value.size.width, height: state.controller!.value.size.height, child: VideoPlayer(state.controller!)),
          ),

          // 只有在 _showControls 为 true 时才显示控制栏和顶部标题
          if (state.showControls) ...[
            // 控制栏
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Colors.transparent, Colors.black54]),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      children: [
                        //播放/暂停按钮
                        IconButton(
                          icon: Icon(state.isPlaying ? Icons.pause_circle_filled : Icons.play_circle_filled, color: Colors.white, size: 30),
                          onPressed: viewModel.togglePlayPause,
                        ),
                        // 进度条
                        Expanded(
                          child: Slider(
                            min: 0,
                            max: state.controller!.value.duration.inSeconds.toDouble(),
                            value: state.sliderValue,
                            onChanged: (value) {
                              viewModel.seekTo(value);
                            },
                          ),
                        ),
                        //时长显示
                        Text('${viewModel.formatDuration(state.controller!.value.position)} / ${viewModel.formatDuration(state.controller!.value.duration)}', style: TextStyle(color: Colors.white)),
                        //横竖屏切换按钮
                        IconButton(
                          icon: Icon(state.isFullScreen ? Icons.fullscreen_exit : Icons.fullscreen, color: Colors.white, size: 30),
                          onPressed: viewModel.toggleFullScreen,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            // 顶部时间显示
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: Center(
                child: Container(
                  padding: EdgeInsets.only(left: 12, right: 12),
                  color: Colors.black54,
                  child: Text(widget.videoName, style: TextStyle(color: Colors.white)),
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    final VideoPlayState state = ref.watch(videoPlayViewModelProvider);
    state.controller?.dispose();
    viewModel.cancelHideTimer(); // 清理计时器
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  }
}
